package main

import (
	"fmt"
	"log"
	"reflect"
	"strings"
	"zhuban/cache"
	"zhuban/curl"
	"zhuban/model"
	"zhuban/tools"
)

func main() {

	var productList []curl.Product
	err := cache.Get("product.json", &productList, func() (any, error) {
		return curl.GetList(1, 10)
	})
	if err != nil {
		panic(err)
	}

	headers := make([]string, 0)
	records := make([][]string, 0)

	// Get the field names as headers
	t := reflect.TypeOf(model.Motherboard{})
	for i := 0; i < t.NumField(); i++ {
		headers = append(headers, t.Field(i).Tag.Get("json"))
	}

	for _, product := range productList {
		if strings.Contains(product.Name, "X99") {
			fmt.Println(product.Name)
			var info model.Motherboard
			err := cache.Get(product.Name+".json", &info, func() (any, error) {
				info, err := curl.Info(product)
				return info, err
			})
			if err != nil {
				log.Println(err)
				continue
			}

			info.Model = product.Name

			record := make([]string, len(headers))
			v := reflect.ValueOf(info)
			for i := 0; i < v.NumField(); i++ {
				record[i] = v.Field(i).String()
			}

			records = append(records, record)
		}
	}

	err = tools.WriteCsv("x99", headers, records)
	if err != nil {
		log.Println(err)
	}
}
